﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace Celeriq.LogReader
{
	public partial class MainForm : Form
	{
		public MainForm()
		{
			InitializeComponent();
		}

		private void cmdFile_Click(object sender, EventArgs e)
		{
			var dialog = new OpenFileDialog();
			dialog.Title = "Open Log File";
			dialog.Filter = "Celeriq Logs (*.query.log)|*.query.log";
			if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
			{
				txtFile.Text = dialog.FileName;
				this.ProcessFile(txtFile.Text);
			}
		}

		private void ProcessFile(string fileName)
		{
			var urlList = new Dictionary<string, int>();
			long totalTime = 0;
			long cacheHits = 0;
			long totalHits = 0;
			double totalResults = 0;

			using (var sr = File.OpenText(fileName))
			{
				var text = sr.ReadLine();
				while (!sr.EndOfStream)
				{
					if (!string.IsNullOrEmpty(text) && !text.StartsWith("#"))
					{
						var arr = text.Split('\t');
						if (arr.Length == 6)
						{
							var isError = false;

							int time;
							if (!int.TryParse(arr[3], out time))
								isError = true;

							long resultCount;
							if (!long.TryParse(arr[2], out resultCount))
								isError = true;

							if (!isError)
							{
								totalResults += resultCount;
								totalHits++;
								var isCache = (arr[4] == "1");

								if (!isCache)
								{
									totalTime += time;
								}
								else
								{
									cacheHits++;
								}

								if (urlList.ContainsKey(arr[5]))
									urlList[arr[5]]++;
								else
									urlList.Add(arr[5], 1);

							}

						}
						else
						{
							System.Diagnostics.Debug.Write("");
						}
					}
					text = sr.ReadLine();
				}
			}

			//Display page
			var computedHits = (totalHits - cacheHits);
			if (computedHits <= 0)
				lblAverageTime.Text = "N/A";
			else
				lblAverageTime.Text = (totalTime / (totalHits - cacheHits)).ToString("###,###,##0.0") + " ms";

			lblCacheHits.Text = cacheHits.ToString("###,###,###,##0");

			if (totalHits == 0)
				lblCacheRatio.Text = "N/A";
			else
				lblCacheRatio.Text = ((cacheHits * 100.0) / totalHits).ToString("##0.00") + "%";

			lblTotalHits.Text = totalHits.ToString("###,###,###,##0");
			lblUniqueHits.Text = urlList.Count.ToString("###,###,###,##0");

			if (totalHits == 0)
				lblAverageResults.Text = "N/A";
			else
				lblAverageResults.Text = (totalResults / totalHits).ToString("###,###,###,##0");

		}
	}
}
